/**
  ******************************************************************************
  * File Name          : weightbsp.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "bsp.h"

#define RS422_DIR_Pin                       GPIO_PIN_2
#define RS422_DIR_GPIO_Port                 GPIOC
#define RS422_DIR(x)                        x?(GPIO_BOP(RS422_DIR_GPIO_Port) = (uint32_t)RS422_DIR_Pin):(GPIO_BC(RS422_DIR_GPIO_Port) = (uint32_t)RS422_DIR_Pin)

/* USART3 init function */
void RS422_BspInit(void)
{
	/* enable GPIO clock */
	rcu_periph_clock_enable(RCU_GPIOA);
	rcu_periph_clock_enable(RCU_GPIOC);
	
	/* enable USART clock */
	rcu_periph_clock_enable(RCU_USART1);
	
//	RS422_DIR(1);
//	gpio_mode_set(RS422_DIR_GPIO_Port, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, RS422_DIR_Pin);
//	gpio_output_options_set(RS422_DIR_GPIO_Port, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, RS422_DIR_Pin);
//	
	/* configure the USART0 Tx pin and USART0 Rx pin */
	gpio_af_set(GPIOA, GPIO_AF_7, GPIO_PIN_2|GPIO_PIN_3);
	
	/* configure USART0 Tx as alternate function push-pull */
	gpio_mode_set(GPIOA, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_2|GPIO_PIN_3);
	gpio_output_options_set(GPIOA, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_2|GPIO_PIN_3);
	
	/* USART configure */
	usart_deinit(USART1);
	usart_baudrate_set(USART1, 9600u);
	usart_word_length_set(USART1, USART_WL_8BIT);
	usart_parity_config(USART1, USART_PM_NONE);
	usart_stop_bit_set(USART1, USART_STB_1BIT);
	usart_receive_config(USART1, USART_RECEIVE_ENABLE);
	usart_transmit_config(USART1, USART_TRANSMIT_ENABLE);
	usart_halfduplex_disable(USART1);
	usart_synchronous_clock_disable(USART1);
	
	/* 200M主频下,115200波特率超时时间约为每个计数8.68us */
	usart_receiver_timeout_threshold_config(USART1, 10000);
	usart_receiver_timeout_enable(USART1);
	
	nvic_irq_enable(USART1_IRQn, 6, 0);
	usart_interrupt_enable(USART1, USART_INT_RBNE);
	usart_interrupt_enable(USART1, USART_INT_RT);
	
	usart_enable(USART1);
}

void RS422_Sendbuf(const uint8_t *buf, uint32_t len)
{
	uint32_t i;
  
	for(i=0; i<len; i++)
	{
    USART_DATA(USART1) = (buf[i]& (uint16_t)0x01FFu);
    while(!(USART_STAT0(USART1) & USART_STAT0_TBE));
	}
	
	while(!(USART_STAT0(USART1) & USART_STAT0_TC));
}

extern void RS422_BreakIsr(void);
extern void RS422_RecvIsr(uint8_t dat);

void USART1_IRQHandler(void)
{
	if(usart_interrupt_flag_get(USART1, USART_INT_FLAG_RBNE) != RESET)
	{
		RS422_RecvIsr(USART_DATA(USART1));
	}
	
	if(usart_interrupt_flag_get(USART1, USART_INT_FLAG_RT) != RESET)
	{
		usart_interrupt_flag_clear(USART1, USART_INT_FLAG_RT);
		
		RS422_BreakIsr();
	}
}

